package com.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.security.core.proterties.LoginType;
import com.security.core.proterties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求成功后登陆页面
 *
 * @author xuweizhi
 * @date 2019/05/15 1:31
 */
@Component("defaultAuthenticationSuccessHandler")
public class DefaultAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Json 工具转换类
     */
    @Autowired
    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 这个方法,登录成功后会被调用
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        logger.info("登陆成功!");

        if(LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())){
            response.setContentType("application/json;charset=UTF-8");
            // 以 json 格式返回认证信息
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        }else{
            // 父类的方法就是跳转
            super.onAuthenticationSuccess(request, response, authentication);
        }


    }

}
